﻿package com.boyaa.shells.tool.filter
{	
	import com.boyaa.debug.Debug;
	import com.boyaa.shells.GlobalConfig;
	
	/**
	 * ...
	 * @author Kevin
	 */
	public class DirtyWordFilter 
	{
		private var _expStr:String = "";				// 正则文本		
		private var _regs:Array = null;					// 正则组
		
		////////////////////////////////////////////////////////////////////////////////		
	
		private const LENGTH:int = 10;					// 正则长度
		
		
		/**
		 * 构造函数
		 */
		public function DirtyWordFilter()
		{
			_regs = new Array();
			init();
		}
		
		/**
		 * 文字过滤器
		 * @param	words
		 * @return
		 */
		public function runFilter(words:String):String
		{
			for (var i:int = 0; i < _regs.length; i++)
			{
				words = words.replace(_regs[i], "*");
			}
			return words;
		}
		
		/**
		 * 把文字转换成星号
		 * @param	content
		 * @return
		 */
		private function changeToStar(content:String):String
		{
			var len:int = content.length;
			content = "";
			for (var i:int = 0; i < len; i++)
			{
				content += "*";
			}
			return content;
		}
		
		/**
		 * 初始化
		 */
		private function init():void
		{
			_expStr = getDirtyWords();
			//var reg:RegExp =/\n\s*/g;
			var reg:RegExp =/\n/g;
			_expStr = _expStr.replace(reg, "");
			
			// 格式正则表达式
			var strs:Array = _expStr.split(/\r/g);			
			strs.shift();
			strs.pop();
			
			/* 请不要删除 用于排序生成 DirtyWordLibrary.as
			strs.sort(function(a:String,b:String):int {
				 if (a.length < b.length) 
				 { 
					return 1; 
				 } 
				 else if (a.length > b.length) 
				 { 
					return -1; 
				 } 
				 else 
				 { 
					return 0; 
				 }
			});			
			*/
			strs.forEach(callBack)
			
			
			_expStr = strs.toString().replace(/,/g, "|");	
			
			// 初始化正则组			
			var exps:Array = _expStr.split(/SSS/g);			
			for (var i:int = 0; i < exps.length; i++)
			{				
				var myStr:String = exps[i];	
				
				if (myStr == "")
				{
					continue;
				}
				if(myStr.charAt(myStr.length-1) == '|')
					myStr = myStr.substr(0, myStr.length - 1);				
				_regs.push(new RegExp(myStr, "gi"));
			}
		}
		
		/**
		 * 数组回调函数
		 * @param	item
		 * @param	index
		 * @param	array
		 */
		private function callBack(item:String, index:int, array:Array):void
		{
			//trace(item);
			//var reg:RegExp =/\s+/g;
			//item = item.replace(reg, "");			
			array[index] = "(" + item + ")";
			if (index % LENGTH == 0)
				array[index] = "SSS" + array[index];
				
				
		}		
		
	
			
		/**
		 * 获取骂人词汇
		 * @return
		 */
		private function getDirtyWords():String
		{
			var str:String = _dirtyXML.toString();
			return str;
		}
		
	}
	
}
include "DirtyWordLibrary.as";